package com.android.example.app3;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.io.File;
import java.util.List;

public class ImageAdapter_list extends RecyclerView.Adapter<ImageAdapter_list.ViewHolder> {
    private final List<ImageItem> imageItems;
    private ItemRemovedListener itemRemovedListener;
    private Context context;

    // 构造函数设置监听器
    public void setItemRemovedListener(ItemRemovedListener listener) {
        this.itemRemovedListener = listener;
    }

    public void context(Context context) {
        this.context = context;
    }
    public ImageAdapter_list(List<ImageItem> imageItems) {
        this.imageItems = imageItems;

    }

    public List<ImageItem> getImageItems() {
        return imageItems;
    }


    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        // 创建一个新的ViewHolder，它包含用于显示图片的ImageView
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.image_list_item_with_title, parent, false);
        return new ViewHolder(view);
    }

    @SuppressLint("QueryPermissionsNeeded")
    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, @SuppressLint("RecyclerView") int position) {
        // 从列表中获取ImageItem
        ImageItem imageItem = imageItems.get(position);
        // 图片的文件路径
        Uri imageUri = imageItem.getImageUri();
        Context context = imageItem.getContext();
//        // 使用Glide加载图片
//        Glide.with(holder.itemView.getContext())
//                .load(imageUri)
//                .into(holder.imageView);
        // 设置文件名
        holder.fileNameTextView.setText(imageItem.getFileName());
        //查看图片
        // 设置图片点击监听器
        holder.fileNameTextView.setOnClickListener(v -> {

//            Toast.makeText(context, "可查看图片的"+imageUri, Toast.LENGTH_SHORT).show();

            Intent intent = new Intent(context, MainActivity2.class);
            intent.putExtra("image_uri", imageUri);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
        });

        //删除图片代码
        holder.delButton.setOnClickListener(v -> {
            if (position != RecyclerView.NO_POSITION && position <= imageItems.size()) {
                AlertDialog.Builder builder = new AlertDialog.Builder(context);
                String fileName = imageItem.getFileName();
                builder.setTitle("正在删除图片操作")
                        .setMessage("是否删除图片" + fileName)
                        .setPositiveButton("确认", (dialog, id) -> {
                            // 用户点击了确认按钮，你可以在这里执行相应操作
//                            boolean deleted = deleteImageWithKnownPath(imageItem.getFilePath());
                            boolean deleted = deleteImageUri(context, imageUri, fileName);
                            if (deleted) {
                                for (int i = 0; i < imageItems.size(); i++) {
                                    if (imageItems.get(i).getFileName().equals(fileName)) {
                                        imageItems.remove(i);
                                        notifyItemRemoved(i); // 通知适配器数据集已更改
                                        break;
                                    }
                                }
                            } else {
                                Toast.makeText(context, fileName + "删除图片失败", Toast.LENGTH_SHORT).show();
                                Log.e("删除图片", "删除图片失败");
                            }
                        })
                        .setNegativeButton("取消", (dialog, id) -> {
                            // 用户点击了取消按钮，你可以在这里执行相应操作
                            // 这里不需要做任何事情，因为用户选择了取消操作
                        })
                        .setIcon(android.R.drawable.ic_dialog_alert)
                        .show();
            } else {
                Toast.makeText(context, "图片文件无法删除", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private boolean deleteImageUri(Context context, Uri imageUri, String fileName) {
        // 使用 ContentResolver 删除图片
        try {
            // 获取 ContentResolver 实例
            ContentResolver contentResolver = context.getContentResolver();
            // 使用 delete 方法删除 Uri 指向的文件
            int deleted = contentResolver.delete(imageUri, null, null);
            if (deleted > 0) {
                // 文件删除成功
                Log.d("DeleteImage", "Image deleted successfully.");
                // 通知Activity数据已更改
                if (itemRemovedListener != null) {
                    itemRemovedListener.onItemRemoved(fileName);
                }
                return true;
            } else {
                // 文件删除失败
                Log.d("DeleteImage", "Image could not be deleted.");
                return false;
            }
        } catch (Exception e) {
            // 处理异常
            Log.e("DeleteImage", "图片文件不存在");
            Log.e("DeleteImage", "图片文件不存在");
            return true;
        }
    }

    public boolean deleteImageWithKnownPath(String imagePath) {
        // 根据图片路径创建File对象
        File imageFile = new File(imagePath);
        // 检查文件是否存在且为文件
        if (imageFile.exists() && imageFile.isFile()) {
            // 尝试删除文件
            boolean isDeleted = imageFile.delete();
            if (isDeleted) {
                Log.i("DeleteImage", "图片已成功删除");
                Toast.makeText(context, imagePath + "删除图片成功", Toast.LENGTH_SHORT).show();
                return true;
            } else {
                Log.e("DeleteImage", "删除图片失败");
                Toast.makeText(context, imagePath + "删除图片失败", Toast.LENGTH_SHORT).show();
                return false;
            }
        } else {
            Log.e("DeleteImage", "图片文件不存在");
            return true;
        }

    }

    @Override
    public int getItemCount() {
        return imageItems.size();
    }

    // 当有新图片时
    public void addItem(ImageItem newImageItem) {
        // 将新图片添加到列表的开头
        imageItems.add(0, newImageItem);
        // 通知适配器有新项插入到位置0
        notifyItemInserted(0);


    }


    public static class ViewHolder extends RecyclerView.ViewHolder {
        //        public ImageView imageView;
        ImageButton delButton;
        TextView fileNameTextView;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            // 初始化ImageView和其他UI组件
//            imageView = itemView.findViewById(R.id.image_view);
            fileNameTextView = itemView.findViewById(R.id.title_text_view);
            delButton = itemView.findViewById(R.id.delButton);
            //查看图片
        }
    }

}